package common

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"net"
)

//一个基本packet的封装
type Packet struct {
	Type  uint8
	Ver  uint8
	Time uint16
	Length uint16
	Data []byte
}

//固定包头
const PacketHeadLen  = 6
const PacketXTLimit  = 4096

//从前面就可以构造一个packet对象了
func NewPacketHead(head []byte) (*Packet,error) {

	//做一些参数检查
	if head[1] == 0 {
		return nil,fmt.Errorf("bad input")
	}

	return &Packet{
		Type:   head[0],
		Ver:    head[1],
		Time:binary.BigEndian.Uint16(head[2:4]),
		Length:binary.BigEndian.Uint16(head[4:6]),
	}, nil
}

//从tcp流读取数据
func  ReadPacketFromTcp(conn *net.TCPConn) (packet *Packet, err error) {

	var (
		headBytes []byte = make([]byte, PacketHeadLen)
		length    uint16
	)

	fmt.Printf("headBytes：%X", headBytes)

	// read length
	if _, err := io.ReadFull(conn, headBytes); err != nil {
		return nil, err
	}

	packet, err = NewPacketHead(headBytes[:])
	if err != nil {
		return nil, err
	}

	if length = packet.Length; length > PacketXTLimit {
		return nil, errors.New("the size of packet is larger than the limit")
	}

	// length 不包含报文头部的长度
	buff := make([]byte, length)
	if length > 0 {
		// read body ( buff = lengthBytes + body )
		if _, err := io.ReadFull(conn, buff); err != nil {
			return packet, err
		}else{
			packet.Data  = buff
		}
	}
	return packet, nil
}
